package com.mall.sso.web.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.mall.pojo.TaotaoResult;
import com.mall.sso.service.TokenService;
import com.mall.utils.CookieUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * @description 登录之前判断用户是否已经登录避免重复登录
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = CookieUtils.getCookieValue(request, "token");
        //验证token
        TaotaoResult taotaoResult = tokenService.verifyToken(token);
        //用户未登录或者登录已过期
        if (taotaoResult == null || taotaoResult.getStatus() != 200){
            return true;
        }
        //用户已经登录,重定向到首页,ajax请求被拦截到无法重定向,因此这里直接返回登录成功提示
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        String json = JSONObject.toJSONString(taotaoResult);
        response.getWriter().write(json);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
